package com.prs.crm.action.hr;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.JohnLan.OutPutEnpassword;
import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.cdxh.SerialNumberss;
import com.prs.crm.domain.hr.Dept;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.hr.Salary;
import com.prs.crm.domain.hr.ShareEim;
import com.prs.crm.domain.meeting.MeetSource;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeCommon;
import com.prs.crm.domain.sys.Log;
import com.prs.crm.exception.InValidDeleteException;
import com.prs.crm.service.cdxh.SerialNumberssService;
import com.prs.crm.service.hr.DeptService;
import com.prs.crm.service.hr.PersonService;
import com.prs.crm.service.hr.RoleService;
import com.prs.crm.service.hr.SalaryService;
import com.prs.crm.service.person.ShareEimService;
import com.prs.crm.service.sys.CodeCommonService;
import com.prs.crm.service.sys.CodeService;
import com.prs.crm.service.sys.LogService;

public class PersonAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6136720957125121468L;
	private Person person;
	private PersonService personService;
	private DeptService deptService;
	private RoleService roleService;
	private LogService logService;
	private PaginationSupport pagination;
	private String deptIds;

	private CodeCommon codeCommon;
	private CodeCommonService codeCommonService;
	private String sname;
	private Code code;
	private CodeService codeService;
	private String Encode;
	private Collection<CodeCommon> codelist;
	private String pass;
	private Integer ids = 0;
	private String rowdata;
	private SerialNumberss serialNumberss;

	private SerialNumberssService serialNumberssService;
	private Integer[] perids;
	private Connection con;
	private Statement stmt;
	private ResultSet rs;
	private ResultSet rs1;
	
	private ShareEimService shareEimService;
	public ShareEimService getShareEimService() {
		return shareEimService;
	}

	public void setShareEimService(ShareEimService shareEimService) {
		this.shareEimService = shareEimService;
	}

	public Integer[] getPerids() {
		return perids;
	}

	public void setPerids(Integer[] perids) {
		this.perids = perids;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	private Integer[] personIds;
	private String affirmPwd;
	private String currentDate;

	private SalaryService salaryService;

	private Collection<Person> persons;
	private List<Salary> salarys;

	private TreeNode root;

	@Action("listPerson")
	public String execute() {
		return SUCCESS;
	}

	@Action("listPersonByDept")
	public String listPersonByDept() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Person.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.in("dept", this.getPersonService()
				.convertToDept(deptIds)));
		this.setPagination(this.getPersonService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	
	@Action("viewPersonByDept")
	public String viewPersonByDept(){
		DetachedCriteria criteria=this.getPaginationHelper().createQuery(Person.class);
		pagination=this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPersonService().listByPage(criteria, pagination));
		return SUCCESS;
	}

	@Action("listManagerPerson")
	public String listManagerPerson() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Person.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPersonService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("selectPerson")
	public String selectPerson() {
		return SUCCESS;
	}
	
	@Action("selectPersons")
	public String selectPersons(){
		return SUCCESS;
	}

	@Action(value = "exportHr", results = { @Result(name = "success", type = "jasper", params = {
			"location", "/reports/hr.jasper", "format", "PDF", "dataSource",
			"persons" }) })
	public String export() {
		this.setPersons(this.getPersonService().findAll());
		return SUCCESS;
	}

	@Action(value = "checkNoticeName", results = { @Result(name = "success", type = "json", params = {
			"root", "rowdata" }) })
	public String checkNoticeName() throws UnsupportedEncodingException {
		String inputName = URLDecoder.decode(sname, "utf-8");
		List<Person> plist = this.getPersonService().getAllPersons();
		int states = 0;
		String idz = "";
		for (Person p : plist) {
			if (inputName.equals(p.getUserName())) {
				states++;
				idz = p.getId() + "";
			}
		}
		if (states > 0) {
			this.rowdata = idz;
		} else {
			this.rowdata = "B";
		}

		return SUCCESS;
	}

	public void setPersons(Collection<Person> persons) {
		this.persons = persons;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public Collection<Person> getPersons() {
		return persons;
	}

	@Action(value = "loadPersonTree", results = { @Result(name = "success", type = "json", params = {
			"root", "root" }) })
	public String loadTree() {
		root = new TreeNode();
		root.setId("-1");

		TreeNode firstNode = new TreeNode();
		firstNode.setId("0");
		firstNode.setText("人员选择");

		Collection<Dept> depts = this.getDeptService().getRootDepts();

		for (Dept depart : depts) {
			TreeNode node = new TreeNode();
			node.setText(depart.getName());
			node.setId("dept-" + depart.getId().toString());
			firstNode.addChildNode(node);
			addDepartNode(node, depart);
			addPersonNode(node, depart);
		}

		root.addChildNode(firstNode);
		return SUCCESS;
	}
	@Action(value = "loadPersonTrees", results = { @Result(name = "success", type = "json", params = {
			"root", "root" }) })
	public String loadTrees() {
		root = new TreeNode();
		root.setId("-1");

		TreeNode firstNode = new TreeNode();
		firstNode.setId("0");
		firstNode.setText("人员选择");

		Collection<Dept> depts = this.getDeptService().getRootDepts();

		for (Dept depart : depts) {
			TreeNode node = new TreeNode();
			node.setText(depart.getName());
			node.setId("dept-" + depart.getId().toString());
			firstNode.addChildNode(node);
			addDepartNode(node, depart);
			addPersonNode(node, depart);
		}

		root.addChildNode(firstNode);
		return SUCCESS;
	}

	private void addDepartNode(TreeNode parent, Dept dept) {
		for (Dept depart : dept.getChilds()) {
			TreeNode node = new TreeNode();
			node.setText(depart.getName());
			node.setId("dept-" + depart.getId().toString());
			parent.addChildNode(node);
			addDepartNode(node, depart);
			addPersonNode(node, depart);
		}
	}

	private void addPersonNode(TreeNode parent, Dept dept) {
		for (Person person : this.getPersonService().findByDept(dept)) {
			TreeNode node = new TreeNode();
			if (person.getResume() != null)
				node.setText(person.getResume().getName());
			else
				node.setText(person.getLoginCode());
			node.setId(person.getId().toString());
			parent.addChildNode(node);
		}
	}

	@Action("alterPerson")
	public String alter() {
		return SUCCESS;
	}

	@Action("alterPersonByDept")
	public String alterPersonByDept() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Person.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.in("dept", this.getPersonService()
				.convertToDept(deptIds)));
		this.setPagination(this.getPersonService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listSerchPerson")
	public String listSerchPerson() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Person.class);
		criteria.createAlias("role", "rL");
		criteria.createAlias("rL.type", "tt");
		criteria.add(Restrictions.eq("tt.name", "114联通"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPersonService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listUpdatePerson")
	public String listUpdatePerson() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Person.class);
		criteria.createAlias("role", "rL");
		criteria.createAlias("rL.type", "tt");
		criteria.add(Restrictions.eq("tt.name", "114联通"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPersonService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("viewPerson")
	public String view() {
		return SUCCESS;
	}

	@Action("viewUserPerson")
	public String viewUserPerson() {
		return SUCCESS;
	}
          /**
           * 商家
           * @return
           */
	@Action("viewBusnessUserPerson")
	public String viewBusnessUserPerson() {
		return SUCCESS;
	}
	/**
	 * 电影院
	 * @return
	 */
	@Action("viewMoiveUserPerson")
	public String viewMoiveUserPerson() {
		return SUCCESS;
	}
	/**
	 * 票务
	 * @return
	 */
	@Action("viewTicketUserPerson")
	public String viewTicketUserPerson() {
		return SUCCESS;
	}
	
	@Action("viewUpdateUserPerson")
	public String viewUpdateUserPerson() {
		return SUCCESS;
	}

	@Action("editPerson")
	public String edit() {
		if (person != null && person.getId() != null) {
			//System.out.println(pass + "    1");
			if (pass != null && !"".equals(pass.trim())) {
				//System.out.println(person.getLoginPwd() + "    1     " + pass);
				person.setLoginPwd(pass);
			}
		}
		this.setCurrentDate(ToolKits.currentDate());
		salarys = this.getSalaryService().getAllSalary();
		this.codelist = this.getCodeCommonService().getCodeCommonByCodeType(
				"人员");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "removeUserPerson", results = {
			@Result(name = "success", type = "redirect", location = "listUpdatePerson"),
			@Result(name = "none", type = "redirect", location = "listUpdatePerson"),
			@Result(name = "error", type = "chain", location = "listUpdatePerson") })
	public String removeUserPerson() {

		if (ids > 0) {
			Person per = this.getPersonService().get(ids);

			
		
			
			//日志2
			 List<Log>    logList2=this.getLogService().ByPersons(per);
			
			
			int inits = 0;
		
		
			if (inits > 0) {
				this.setPrompt("该用户有关联数据不能删除");
				return "error";
			} else {
				this.getPersonService().submit(per);
				per.setRole(null);
				this.getPersonService().saveOrUpdate(per);
				
				this.getPersonService().remove(per);
				this.setPrompt("删除操作成功！");
				return SUCCESS;
			}

		} else {
			this.setPrompt("删除失败！");
			return "error";
		}

	}

	@Clew(results = { "success", "none" })
	@Action(value = "personUpdate", results = {
			@Result(name = "success", type = "redirect", location = "listUpdatePerson"),
			@Result(name = "none", type = "redirect", location = "listUpdatePerson"),
			@Result(name = "error", type = "chain", location = "listUpdatePerson") })
	public String personUpdate() {
		person.setRecordTime(new Date());
		person.setRole(person.getRole());
		person.setUploadMaxVolume(person.getUploadMaxVolume());
		person.setLoginPwd(OutPutEnpassword.outPassword(person.getLoginPwd()));
		this.getPersonService().submit(person);
		this.setPrompt("变更操作成功！");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "savePerson", results = {
			@Result(name = "success", type = "redirect", location = "editPerson"),
			@Result(name = "none", type = "redirect", location = "alterPerson"),
			@Result(name = "error", type = "chain", location = "editPerson") })
	public String save() throws SQLException {
		
        List<Person> per=this.getPersonService().getAllPersons();
        int diacInit=0;
        for(Person p:per){
        	if(p.getLoginCode().equals(person.getLoginCode())){
        		diacInit++;
        	}
        }
//        if (isnull(person.getUserEmail())) {
//    		if (emailFormat(person.getUserEmail())) {
//    			this.addActionError("邮箱格式不正确");
//    			return ERROR;
//    		}
//    	}
        if(diacInit>0){
        	this.setPrompt("提交人员失败，登录名重复");
    		return ERROR;
        }else{
		person.setMarkName("否");
		person.setState(Constrains.TASK_AUDITING);
		person.setTstate(1);
		person.setLoginPwd(OutPutEnpassword.outPassword(person.getLoginPwd()));//将密码加密
		this.getPersonService().save(person);
		this.setPrompt("提交人员成功");
		return SUCCESS;
		}
		
	}

	@Action(value = "removePerson", results = {
			@Result(name = "success", type = "redirect", location = "alterPerson"),
			@Result(name = "error", type = "chain", location = "alterPerson") })
	public String remove() {
		try {
			if (personIds == null) {
				this.addActionError("请选择要删除的人员");
				return ERROR;
			}
			this.getPersonService().batchRemove(personIds);
			return SUCCESS;
		} catch (InValidDeleteException e) {
			return ERROR;
		}
	}
	@Action("updatePassWord")
	public String updatePassWord(){
		return SUCCESS;
	}
	@Action(value = "savePassWord", results = {
			@Result(name = "success", type = "redirect", location = "updatePassWord?person=${person.getId()}"),
			@Result(name = "error", type = "chain", location = "updatePassWord?person=${person.getId()}") })
	public String savePassWord(){
		person.setLoginPwd(OutPutEnpassword.outPassword(person.getLoginPwd()));//将密码加密
		this.getPersonService().submit(person);	
		return SUCCESS;
	}
	@Action("editPersonSet")
	public String editPersonSet(){
		this.person=this.getPersonService().get(AppContext.getAccountContext().getUser().getId());
		return SUCCESS;
	}
	@Action("editPassword")
	public String editPassword(){
		this.person=this.getPersonService().get(AppContext.getAccountContext().getUser().getId());
		return SUCCESS;
	}
	
	@Action("editPersonLimit")
	public String editPersonLimit(){
		if (perids!=null) {
			person=this.getPersonService().get(perids[0]);
		}
		System.out.println(person.getId());
		return SUCCESS;
	}
	@Action("listPersonLimit")
	public String listPersonLimit(){
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(Person.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getPersonService().listByPage(criteria,pagination));
		return SUCCESS;
	}
	@Action(value = "savePersonLimit", results = {
			@Result(name = "success", type = "redirect", location = "listPersonLimit"),
			@Result(name = "error", type = "chain", location = "editPersonLimit") })
	public String savePersonLimit(){
		this.getPersonService().submit(person);
		return SUCCESS;
	}
	
	@Action("editPersonShare")
	public String editPersonShare(){		
		return SUCCESS;
	}

	@Action(value = "savePersonColumn", results = {
			@Result(name = "success", type = "redirect", location = "editPersonShare?person=${person.getId()}"),
			@Result(name = "error", type = "chain", location = "editPersonShare") })
	public String savePersonColumn() throws SQLException{
		person.setAllfieldname("");
		this.getPersonService().submit(person);
		Properties pro=new Properties();
		
		String path = Thread.currentThread().getContextClassLoader().getResource("connect.properties").getPath();
		try {
			pro.load(new FileInputStream(path));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String ClassName=pro.getProperty("ClassName");
		String userName=pro.getProperty("userName");
		String userPass=pro.getProperty("userPass");
		String url1=pro.getProperty("url1");
		try {
			Class.forName(ClassName);
			con = DriverManager.getConnection(url1, userName, userPass);
			stmt = this.con.createStatement();
			try{
				PreparedStatement pst = con.prepareStatement("select * from "+person.getTableName());
				rs1=pst.executeQuery();
			}catch (Exception e) {
				this.addActionError("请确认表名是否输入正确");
				return ERROR;
			}
			ResultSetMetaData metaData = rs1.getMetaData();
			 if (rs1.next()) {
				 for (int i = 1; i <= metaData.getColumnCount(); i++) {
				    if (person.getAllfieldname()==null || "".equals(person.getAllfieldname().trim())) {
				    	person.setAllfieldname(metaData.getColumnName(i));
					}else{
						person.setAllfieldname(person.getAllfieldname()+","+metaData.getColumnName(i));
					}
				    this.getPersonService().submit(person);
				 } 	
			 }
			 rs1.close();
			 con.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	@Clew(results = { "success" })
	@Action(value = "savePersonShare", results = {
			@Result(name = "success", type = "redirect", location = "alterPerson"),
			@Result(name = "error", type = "chain", location = "editPersonShare") })
	public String savePersonShare() throws SQLException{
		person.setTstate(2);
		this.getPersonService().submit(person);
		this.getPersonService().saveCenterTable(person);
		this.setPrompt("共享成功！");
		return SUCCESS;
	}
	
	public void setSalarys(List<Salary> salarys) {
		this.salarys = salarys;
	}

	public List<Salary> getSalarys() {
		return salarys;
	}

	public void setSalaryService(SalaryService salaryService) {
		this.salaryService = salaryService;
	}

	public SalaryService getSalaryService() {
		return salaryService;
	}

	public String getDeptIds() {
		return deptIds;
	}

	public void setDeptIds(String deptIds) {
		this.deptIds = deptIds;
	}

	public CodeCommon getCodeCommon() {
		return codeCommon;
	}

	public void setCodeCommon(CodeCommon codeCommon) {
		this.codeCommon = codeCommon;
	}

	public CodeCommonService getCodeCommonService() {
		return codeCommonService;
	}

	public void setCodeCommonService(CodeCommonService codeCommonService) {
		this.codeCommonService = codeCommonService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeCommon> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeCommon> codelist) {
		this.codelist = codelist;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	public SerialNumberss getSerialNumberss() {
		return serialNumberss;
	}

	public void setSerialNumberss(SerialNumberss serialNumberss) {
		this.serialNumberss = serialNumberss;
	}

	public SerialNumberssService getSerialNumberssService() {
		return serialNumberssService;
	}

	public void setSerialNumberssService(
			SerialNumberssService serialNumberssService) {
		this.serialNumberssService = serialNumberssService;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public PersonService getPersonService() {
		return personService;
	}

	public void setDeptService(DeptService deptService) {
		this.deptService = deptService;
	}

	public DeptService getDeptService() {
		return deptService;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Integer[] getPersonIds() {
		return personIds;
	}

	public void setPersonIds(Integer[] personIds) {
		this.personIds = personIds;
	}

	public void setAffirmPwd(String affirmPwd) {
		this.affirmPwd = affirmPwd;
	}

	public String getAffirmPwd() {
		return affirmPwd;
	}

	public void setCurrentDate(String currentDate) {
		this.currentDate = currentDate;
	}

	public String getCurrentDate() {
		return currentDate;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public TreeNode getRoot() {
		return root;
	}

	public Integer getIds() {
		return ids;
	}

	public void setIds(Integer ids) {
		this.ids = ids;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public String getRowdata() {
		return rowdata;
	}

	public void setRowdata(String rowdata) {
		this.rowdata = rowdata;
	}

	

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	
	public boolean isnull(String str) {
		boolean s=true;
		if (str.trim().equals("") || str == null) {
			s= false;
		}
		return s;
	}
	public boolean emailFormat(String email) {
		boolean tag = false;
		final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(email);
		if (!mat.find()) {
			tag = true;
		}
		return tag;
	}

	@Action(value = "loadPersonBySubordinate", results = { @Result(name = "success", type = "json", params = {
			"root", "root" }) })
	public String loadPersonBySubordinate() {
		root = new TreeNode();
		root.setId("-1");

		TreeNode firstNode = new TreeNode();
		firstNode.setId("0");
		firstNode.setText("人员选择");

		Collection<Person> meetSources = this.getPersonService().getRootPersonBySubordinate();

		for (Person meetSource : meetSources) {
			String[] pers=meetSource.getSubordinateId().split(",");
			
			for (String per : pers) {
				TreeNode node = new TreeNode();
				node.setId(per.toString());
				Person ps=this.getPersonService().getPersonById(Integer.parseInt(per));
				if (ps!=null) {
					node.setText(ps.getResume().getName());
				}
				firstNode.addChildNode(node);	
			}
//			node.setText(meetSource.getResume().getName());	
		}
		root.addChildNode(firstNode);
		return SUCCESS;
	}
}
